package edu.zut.cs.javaee.manager.student;

import edu.zut.cs.javaee.manager.base.exception.GlobalException;
import edu.zut.cs.javaee.manager.base.util.Page;
import edu.zut.cs.javaee.manager.base.util.PageList;
import edu.zut.cs.javaee.manager.student.dao.StudentDao;
import edu.zut.cs.javaee.manager.student.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;


/**
 * 学生service        
 */
@Service
@Transactional
public class StudentService {

    @Autowired
    private StudentDao studentDao;

    public List getUserInfo(String userName, String passWord) {

        return studentDao.findList("from Student where name = ?0 and password = ?1",userName,passWord);
    }

    /**
     * 分页查询学生信息
     * @param page
     * @param name
     * @param userId
     * @param role
     * @return
     */
    public PageList<Student> getStudentList(Page page, String name, Integer userId, Integer role) {
        String hql = "from Student  where delFlag = 0";
        if (role == 3) {
            hql += " and id = " + userId;
        }
        if (!ObjectUtils.isEmpty(name)) {
            hql += " and name like '%"+name+"%'";
        }
        return studentDao.findPageListByHql(page,hql);
    }

    /**
     * 新增学生
     * @param s
     * @throws Exception
     */
    @Transactional
    public void add(Student s) throws Exception {
        List<Student> list = studentDao.findList("from Student where xueHao = ?0", s.getXueHao());
        if (!ObjectUtils.isEmpty(list)) {
            throw new GlobalException("系统繁忙，请稍后重试");
        }
        studentDao.save(s);
    }

    /**
     * 学生信息更新
     * @param s
     * @throws Exception
     */
    @Transactional
    public void update(Student s) throws Exception {
        Student student = studentDao.get(s.getId());
        student.setSubject(s.getSubject());
        student.setSex(s.getSex());
        student.setName(s.getName());
        if (!ObjectUtils.isEmpty(s.getPassword())) {
            student.setPassword(s.getPassword());
        }
    }

    /**
     * 删除用户
     * @param s
     * @throws Exception
     */
    @Transactional
    public void delete(Student s) throws Exception {
        Student student = studentDao.get(s.getId());
        student.setDelFlag(1);
        studentDao.update(student);
    }
}
